package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("DiscoverylinkRestController")
public class DiscoverylinkRestController extends CmiEmaController {

	/**
	 * Create a new Discoverylink entity
	 * 
	 */
	@RequestMapping(value = "/newDiscoverylink", method = RequestMethod.POST)
	@ResponseBody
	public Object newDiscoverylink(@RequestBody Discoverylink discoverylink) {
		discoverylinkService.saveDiscoverylink(discoverylink);
		return JSONObject
				.parse(cmiPsonService.toJsonString(discoverylinkDAO.findDiscoverylinkByPrimaryKey(discoverylink.getId()), 2));
	}

	@RequestMapping(value = "/restNewDiscoverylink", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewDiscoverylink(@RequestBody String discoverylinkJson) {
		Discoverylink discoverylink = new Gson().fromJson(discoverylinkJson, Discoverylink.class);
		appendReferences(discoverylink);
		discoverylinkService.saveDiscoverylink(discoverylink);
		return JSONObject
				.parse(cmiPsonService.toJsonString(discoverylinkDAO.findDiscoverylinkByPrimaryKey(discoverylink.getId()), 2));
	}

	@RequestMapping(value = "/saveDiscoverylink", method = RequestMethod.PUT)
	@ResponseBody
	public Discoverylink saveDiscoverylink(@RequestBody Discoverylink discoverylink) {
		discoverylinkService.saveDiscoverylink(discoverylink);
		return discoverylinkDAO.findDiscoverylinkByPrimaryKey(discoverylink.getId());
	}

	@RequestMapping(value = "/restSaveDiscoverylink", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveDiscoverylink(@RequestBody String discoverylinkJson) {
		Discoverylink discoverylink = new Gson().fromJson(discoverylinkJson, Discoverylink.class);
		appendReferences(discoverylink);
		CmiPsonService cmiPsonService = new CmiPsonService();
		discoverylinkService.saveDiscoverylink(discoverylink);
		return JSONObject
				.parse(cmiPsonService.toJsonString(discoverylinkDAO.findDiscoverylinkByPrimaryKey(discoverylink.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteDiscoverylink/{discoverylinkId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteDiscoverylink(@PathVariable Integer discoverylinkId) {
		Discoverylink discoverylink = discoverylinkDAO.findDiscoverylinkByPrimaryKey(discoverylinkId);
		discoverylinkService.deleteDiscoverylink(discoverylink);
	}

	@RequestMapping(value = "/restConfirmDeleteDiscoverylinks")
	@ResponseBody
	public Object restConfirmDeleteDiscoverylinks(@RequestBody Set<Integer> deleteDiscoverylinksIds) {
		Set<Discoverylink> deleteDiscoverylinks = discoverylinkDAO.findDiscoverylinksByIds(deleteDiscoverylinksIds);
		Set<Discoverylink> referencedDiscoverylinks = discoverylinkService
				.loadReferenceDiscoverylinks(deleteDiscoverylinks);
		deleteDiscoverylinks.removeAll(referencedDiscoverylinks);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedDiscoverylinks);
		jsonObject.put("deleteEntitys", deleteDiscoverylinks);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteDiscoverylinks")
	@ResponseBody
	public Object restDeleteDiscoverylinks(@RequestBody Set<Discoverylink> deleteDiscoverylinks) {
		Iterator<Discoverylink> iterator = deleteDiscoverylinks.iterator();
		while (iterator.hasNext()) {
			Discoverylink currentDiscoverylink = iterator.next();
			discoverylinkService.deleteDiscoverylink(currentDiscoverylink);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listDiscoverylinks");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadDiscoverylink/{discoverylinkId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadDiscoverylink(@PathVariable Integer discoverylinkId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(discoverylinkDAO.findDiscoverylinkByPrimaryKey(discoverylinkId),
				2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	@RequestMapping(value = "/restLoadDiscoverylinkEvents/{discoverylinkId}/events/{relatedeventId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadDiscoverylinkEvents(@PathVariable Integer discoverylinkId,
			@PathVariable Integer relatedeventId, @RequestBody CmiPagination cmiPagination) {
		Event event = eventDAO.findEventByPrimaryKey(relatedeventId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(event, 2, cmiPagination));
	}

	public void appendReferences(Discoverylink discoverylink) {

		// 引用表是纯联系表的情况
		Set<Event> eventsForDiscoverylink = new HashSet<>();
		for (Event eventForDiscoverylink : discoverylink.getEventsForDiscoverylink()) {
			eventsForDiscoverylink.add(eventService.findEventByPrimaryKey(eventForDiscoverylink.getId()));
		}
		discoverylink.setEventsForDiscoverylink(eventsForDiscoverylink);
	}

	@RequestMapping(value = "/restGetDiscoverylinkEvents/{discoverylinkId}/events", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetDiscoverylinkEvents(@PathVariable Integer discoverylinkId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				discoverylinkDAO.findDiscoverylinkByPrimaryKey(discoverylinkId).getEventsForDiscoverylink(), 2,
				cmiPagination));
	}

	@RequestMapping(value = "/restListDiscoverylinks", method = RequestMethod.GET)
	@ResponseBody
	public Object restListDiscoverylinks() {
		return JSONObject.parse(cmiPsonService.toJsonString(discoverylinkService.loadDiscoverylinks(), 2));
	}

	@RequestMapping(value = "/restListDiscoverylinksPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListDiscoverylinksPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = discoverylinkPaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Discoverylink> discoverylinks = discoverylinkDAO.findAllDiscoverylinks(startResult,
				cmiPagination.getPaginationSize());
		String discoverylinkString = cmiPsonService.toPsonString(discoverylinks, 2, cmiPagination);

		return JSONObject.parse(discoverylinkString);
	}

	@RequestMapping("/discoverylinkSelectBox")
	@ResponseBody
	public JSONObject discoverylinkSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键

			// 被引用键

			case "Event":
				entitySet = eventService.loadEventsByIdSet(searchValue);
				break;
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键

			// 被引用键

			case "Event":
				entitySet = eventDAO.findAllEvents((pageNumber - 1) * paginationSize, paginationSize);
				count = eventService.countEvents();
				break;
			}
		} else {
			switch (selectItem) {
			// 外键

			// 被引用键

			case "Event":
				entitySet = eventDAO.findEventByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = eventService.countEventsByName(queryword);
				break;
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
